import React, {Component, ComponentClass} from 'react';
import Taro from '@tarojs/taro';
import {AtIcon, AtList, AtListItem, AtSearchBar, AtTabs} from 'taro-ui'
import {View, Text, Image, Picker} from '@tarojs/components'
import {CUSTOMER_CLASSIFICATION, RESOURCE_URL, TARO_ENV} from '../../constants/api'
import {vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {newHttp} from "../../utils/request";
import Water from "../components/water-mark/index";
import './customer.scss'

const tabMenus = [
  {id: 0, title: '全部客户'},
  {id: 1, title: '星标客户'},
  {id: 2, title: '有效客户'},
  {id: 3, title: '下单客户'},
  {id: 4, title: '失效客户'}
];

interface stateType {
  tabs: any
  orderList: any
  curTabIndex: number
  todayTime: number
  beforeTime: number
  sevenDayAfter: number
  tomorrowTime: number
  searchResult: any
  searchText: string
  scrollTop: number
  timeTabIndex: number
  isOpenTime: boolean
  info: any
  isEmpty: boolean
}

class Search extends Component {
  state: stateType = {
    isOpenTime: false,
    searchResult: [],
    searchText: '',
    tabs: [],
    todayTime: 0,
    beforeTime: 0,
    sevenDayAfter: 0,
    tomorrowTime: 0,
    curTabIndex: 0,
    scrollTop: 0,
    timeTabIndex: 0,
    info: {
      money: 0,
      num: 0,
      earningsMoney: 0
    },
    isEmpty: false
  }
  page = 1
  total = 0
  length = 10

  searchConfirm() {
    this.page = 1
    this.search(this.page)
  }

  async componentDidShow() {
    this.page = 1
    vcmonitor(this)
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    // 针对蝌蚪屏蔽
    if (process.env.P_ENV !== "kd") {
      this.setState({tabs: [...tabMenus]});
    }
    const n = new Date()
    const todayTime = n.getTime()
    const beforeTime = n.getTime() - (24 * 60 * 60 * 1000)
    const tomorrowTime = n.getTime() + (24 * 60 * 60 * 1000)
    const sevenDayAfter = n.getTime() + (24 * 60 * 60 * 1000 * 6)
    const active = Taro.getCurrentInstance().router.params.active || ''
    let dateStart = Taro.getCurrentInstance().router.params.search_date_start || ''
    if (active == 1) {
      let timeTabIndex = 0
      let dateEnd
      if (dateStart === this.getDate(todayTime)) {
        timeTabIndex = 1
        dateEnd = dateStart
      } else if (dateStart === this.getDate(beforeTime)) {
        timeTabIndex = 2
        dateEnd = dateStart
      } else if (this.getDate(todayTime) <= dateStart && dateStart <= this.getDate(sevenDayAfter - (24 * 60 * 60 * 1000))) {
        timeTabIndex = 3
        dateStart = this.getDate(todayTime)
        dateEnd = this.getDate(sevenDayAfter - (24 * 60 * 60 * 1000))
      } else {
        dateStart = ''
      }
      await this.setStateSync({timeTabIndex, dateStart, dateEnd})
    }
    this.setState({todayTime, beforeTime, sevenDayAfter, tomorrowTime})
    await this.search(this.page)
  }

  setStateSync(state) {
    return new Promise(resolve => {
      this.setState(state, resolve);
    });
  }

  async onReachBottom() {
    console.log("onReachBottom - isEmpty : ", this.state.isEmpty);
    // 避免空数据时多请求
    if (!this.state.isEmpty) {
      this.page++
      await this.search(this.page)
    }
  }

  async search(page) {
    Taro.showLoading({title: "加载中..."})
    const ret = await this.getSearchData(page);
    Taro.hideLoading()
    if (ret && ret.length > 0) {
      if (page === 1) {
        this.setState({
          searchResult: ret
        })
      } else if (page > 1) {
        const oldData = this.state.searchResult;
        this.setState({
          searchResult: [...oldData, ...ret]
        })
      }
    } else {
      if (page === 1) {
        this.setState({
          searchResult: []
        })
      }
    }
  }

  async getSearchData(page) {
    if (typeof page != "number") {
      page = this.page + 1
    }
    const {searchText, curTabIndex, dateStart, dateEnd} = this.state
    const data = {
      page,
      length: 10,
      searchText,
      search_type: curTabIndex,
      search_date_start: dateStart,
      search_date_end: dateEnd
    }
    let result = await newHttp.catchGet(CUSTOMER_CLASSIFICATION, data)
    // 测试
    /*result = {
      recordsFiltered: 1,
      countNum: 0,
      channel: "微信公众号",
      resourceDomain: "https://resource.ivcheng.com",
      draw: "1",
      list: [
        {
          user_id: 1166808,
          offpay_date: "2022-08-11",
          isSeller: 1,
          effective: 0,
          starLabel: 0,
          countOrderNum: 3,
          sumTotalFee: 0.15,
          user: {
            phone: "19819292012",
            nick_name: "。",
            gender: 0,
            photo: "",
            bind_seller_id: 159635
          },
          label: {
            star_label: 0,
            remark: ""
          }
        }
      ],
      recordsTotal: 1
    }*/
    const isEmpty = result && result.list.length < 10 ? true : false // 列表小于10条表示已加载完(已加载完即不再触底翻页)
    this.setState({info: result, isEmpty}, () => {
      console.log("getSearchData - isEmpty : ", this.state.isEmpty)
    })
    if (!result) {
      return false;
    } else {
      result = result.list
    }
    return result || []
  }

  input(value) {
    if (value) {
      this.setState({searchText: value})
    }
  }

  clearSearch() {
    this.setState({searchText: '', searchResult: []}, async () => {
      this.searchConfirm()
    })
  }

  tabClick(index) {
    this.page = 1
    this.setState({curTabIndex: index, searchResult: []}, async () => {
      await this.search(this.page)
    })
  }

  onDateChange(type, e) {
    if (type === 'dateStart') {
      this.setState({dateStart: e.detail.value})
    }
    if (type === 'dateEnd') {
      this.setState({dateEnd: e.detail.value})
    }
  }

  customTime() {
    this.setState({isOpenTime: !this.state.isOpenTime})
  }

  sureBtn() {
    const {dateStart, dateEnd, todayTime, beforeTime, sevenDayAfter, tomorrowTime} = this.state
    this.setState({isOpenTime: false})
    if (dateStart && dateEnd) {
      let timeTabIndex = -1
      if ((dateStart === this.getDate(todayTime) && dateEnd === this.getDate(tomorrowTime)) || dateStart === this.getDate(todayTime) && dateEnd === this.getDate(todayTime)) {
        timeTabIndex = 1
      } else if (dateStart === this.getDate(beforeTime) && dateEnd === this.getDate(todayTime)) {
        timeTabIndex = 2
      } else if (dateStart === this.getDate(todayTime) && (dateEnd <= this.getDate(sevenDayAfter) && dateEnd > this.getDate(todayTime + (24 * 60 * 60 * 1000)))) {
        timeTabIndex = 3
      }
      this.setState({timeTabIndex})
    }
    this.searchConfirm()
  }

  getDate(time) {
    const newTimeDate = new Date(time)
    let now = ''
    now += newTimeDate.getFullYear() + '-'
    now += newTimeDate.getMonth() + 1 < 10 ? '0' + (newTimeDate.getMonth() + 1) : newTimeDate.getMonth() + 1
    now += '-'
    now += newTimeDate.getDate() < 10 ? '0' + newTimeDate.getDate() : newTimeDate.getDate()
    return now
  }

  changeTab(val) {
    const {timeTabIndex, todayTime, beforeTime, sevenDayAfter} = this.state
    if (val !== timeTabIndex) {
      if (val === 1) {
        this.setState({
          timeTabIndex: val,
          dateStart: this.getDate(todayTime),
          dateEnd: this.getDate(todayTime + (24 * 60 * 60 * 1000))
        }, async () => {
          this.searchConfirm()
        })
      } else if (val === 2) {
        this.setState({
          timeTabIndex: val,
          dateStart: this.getDate(beforeTime),
          dateEnd: this.getDate(beforeTime)
        }, async () => {
          this.searchConfirm()
        })
      } else if (val === 3) {
        this.setState({
          timeTabIndex: val,
          dateStart: this.getDate(todayTime),
          dateEnd: this.getDate(sevenDayAfter)
        }, async () => {
          this.searchConfirm()
        })
      } else {
        this.setState({timeTabIndex: val, dateStart: '', dateEnd: ''}, async () => {
          this.searchConfirm()
        })
      }
    }
  }

  render() {
    const {
      searchResult,
      searchText,
      scrollTop,
      tabs,
      curTabIndex,
      timeTabIndex,
      isOpenTime,
      dateStart,
      dateEnd,
      info
    } = this.state
    return (
      <View className='promotionOrderRoot'>
        <GzhAuth />
        <Water />
        <View className='search-top' style={scrollTop >= 90 ? 'position:fixed' : ''}>
          <AtSearchBar onConfirm={this.searchConfirm.bind(this)}
            onClear={this.clearSearch.bind(this)} onActionClick={this.searchConfirm.bind(this)}
            value={searchText} onChange={this.input.bind(this)} placeholder='请输入手机号或客户昵称搜索'
          />
          <AtTabs className='order-tabs' tabList={tabs} current={curTabIndex}
            onClick={this.tabClick.bind(this)}
          />
          <View className='time-filter-item-wrapper'>
            <View className='time-filter-item'>
              <View onClick={this.changeTab.bind(this, 0)}
                className={`time-filter-items ${timeTabIndex === 0 && 'time-active'}`}
              >全部</View>
              <View onClick={this.changeTab.bind(this, 1)}
                className={`time-filter-items ${timeTabIndex === 1 && 'time-active'}`}
              >今日</View>
              <View onClick={this.changeTab.bind(this, 2)}
                className={`time-filter-items ${timeTabIndex === 2 && 'time-active'}`}
              >昨日</View>
              <View onClick={this.changeTab.bind(this, 3)}
                className={`time-filter-items ${timeTabIndex === 3 && 'time-active'}`}
              >近7日</View>
            </View>
            <View className='custom-time' onClick={this.customTime.bind(this)}>自定义时间<AtIcon
              value={isOpenTime ? 'chevron-up' : 'chevron-down'} size='12' color='#ccc'
            /></View>
          </View>
          {isOpenTime && <View className='time-picker-choice'>
            <Picker className='time-picker-choice-picker' mode='date'
              onChange={this.onDateChange.bind(this, 'dateStart')}
            >
              <AtList>
                <AtListItem title='开始日期' extraText={dateStart} />
              </AtList>
            </Picker>
            <Picker className='time-picker-choice-picker' mode='date'
              onChange={this.onDateChange.bind(this, 'dateEnd')}
            >
              <AtList>
                <AtListItem title='结束日期' extraText={dateEnd} />
              </AtList>
            </Picker>
          </View>}
          {isOpenTime && <View className='sure-btn' onClick={this.sureBtn.bind(this)}>确定</View>}
        </View>
        {searchResult && searchResult.length > 0 && <View className='promotion-order-info-wrapper'>
          <View className='promotion-order-top-info'>共<Text className='promotion-order-nums'>{info.recordsTotal}</Text>个客户</View>
          <View className='list-container'>
            {searchResult.map((item: any,  index) =>
              <View key={index} onClick={() => {
                // 针对蝌蚪屏蔽
                if (process.env.P_ENV === "kd") return;
                let mpkey = ''
                const uInfo = Taro.getStorageSync('user') || ''
                if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
                  mpkey = uInfo.mpkey
                }
                Taro.navigateTo({url: '/other/my/customerInfo?userId=' + item.user_id + '&mpkey=' + mpkey})
              }} className='salesman-customer van-cell van-cell--center'
              >
                <View className='van-cell__value van-cell__value--alone'>
                  <View className={`salesman-avatar ${item.effective === 0 && 'salesman-avatar--disabled'}`}>
                    <Image className='salesman-avatar__img'
                      src={item.user.photo || `${RESOURCE_URL}/upload/images/20211120/1637398013770_87.png`}
                    />
                  </View>
                  <View className='salesman-customer__info-block'>
                    <View className='salesman-customer__info'>
                      <View className='salesman-customer__info-top'>
                        {!!item.user &&
                          <Text className='salesman-customer__info-name copy'>{item.user.nick_name}</Text>}
                        {!!item.starLabel && <View className='vip-bar'>
                          <Image src={`${RESOURCE_URL}/upload/images/20211119/1637308886416_130.png`} mode='widthFix'
                            className='vip-bar__icon-star starimg'
                          />
                        </View>}
                      </View>
                      <View className='salesman-customer__info--bill'>
                        <View className='text'>成交额：<Text className='text-num'>{item.sumTotalFee}</Text></View>
                        <View className='text'>订单数：<Text className='text-num'>{item.countOrderNum}</Text></View>
                      </View>
                      <View className='salesman-customer__info--at'>
                        最近下单时间：{item.offpay_date}
                      </View>
                    </View>
                  </View>
                </View>
              </View>
            )}
          </View>
        </View>}
        {isOpenTime && <View className='open-time-over-layout'>
          <View className='over-layout' onClick={() => {
            this.setState({isOpenTime: !isOpenTime})
          }}
          />
        </View>}
        {searchResult.length <= 0 &&
          <View className='listNull' style={`${TARO_ENV === 'weapp' && 'top: 20% !important;'}`}>
            <Image src={`${RESOURCE_URL}/upload/images/20211112/1636708674979_153.png`} mode='widthFix' />
            <View className='text'>暂无数据</View>
          </View>}
        <View style='height: 30px;'></View>
      </View>
    )
  }
}

export default Search as ComponentClass
